package pl.kollek;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

enum position {inChannel, inItem, nowhere};
enum elements {description, link, pubDate, title, unknown};

public class MainActivity extends Activity {
        
        private String channelTitle = "";
        private List<Article> articles = new ArrayList<Article>();

        /** Handler wykorzystywany podczas odczytywania pliku xml */
        private class RSSHandler extends DefaultHandler {
                
                private Article article;
                private position where = position.nowhere;
                private elements item = elements.unknown;
                
                @Override
                public void characters(char[] ch, int start, int length)
                                throws SAXException {
                        super.characters(ch, start, length);
                        
                        if(item != elements.unknown) {
                                String textNode = new String(ch, start, length);
                                
                                //Wewnatrz <channel>
                                if(where == position.inChannel) {
                                        if(item == elements.title) channelTitle = textNode;
                                }
                                //Wewnatrz <item>
                                else if(where == position.inItem) {
                                        if(item == elements.title) article.title = textNode;
                                        else if(item == elements.description 
                                                        && article.description.length() < 256)
                                                                article.description += textNode;
                                        else if(item == elements.link) article.parseToUrl(textNode);
                                }
                        }
                }

                @Override
                public void endElement(String uri, String localName, String qName)
                                throws SAXException {
                        super.endElement(uri, localName, qName);
                        
                        if(localName.equals("item")) {
                                article.description = article.description.replaceAll("\\<.*?\\>", "");
                                articles.add(article);
                                where = position.inChannel;
                                
                        }
                        else if(localName.equals("channel")) where = position.nowhere;
                        else if(item != elements.unknown) item = elements.unknown;
                }

                @Override
                public void startElement(String uri, String localName, String qName,
                                Attributes attributes) throws SAXException {
                        super.startElement(uri, localName, qName, attributes);
                        
                        if(localName.equals("item")){ 
                                where = position.inItem;
                                article = new Article();
                        }
                        else if(localName.equals("title")) item = elements.title;
                        else if(localName.equals("link")) item = elements.link;
                        else if(localName.equals("description")) item = elements.description;
                        else if(localName.equals("pubDate")) item = elements.pubDate;
                        else if(localName.equals("channel")) where = position.inChannel;        
                }
                
        }
        
    /** Called when the activity is first created. */
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            ListView listView = (ListView)findViewById(R.id.list);
            TextView title = (TextView)findViewById(R.id.title);
            
            parseXml("http://www.tvn24.pl/polska.xml");
            
                title.setText(channelTitle);
                fillListView(listView);
                
                listView.setOnItemClickListener(new OnItemClickListener() {
        
                        @Override
                        public void onItemClick(AdapterView<?> arg0, View v, int pos,
                                        long id) {
                                Intent myIntent = new Intent(getApplicationContext(), ArticleActivity.class);
                                myIntent.putExtra("feedTitle", channelTitle);
                                myIntent.putExtra("articleTitle",articles.get(pos).title);
                                myIntent.putExtra("articleContent", articles.get(pos).description);
                                myIntent.putExtra("articleUrl", articles.get(pos).url.toString());
                                startActivity(myIntent);
                        }
                });
        }
    
    /** Metoda wypelniajaca ListView aktywnosci tytulami pobranymi z listy artykulów */
    private void fillListView(ListView list) {
        List<String> item = new ArrayList<String>();
                for (Article article : articles)
                        item.add(article.title);
                
                ArrayAdapter<String> adapter = 
                        new ArrayAdapter<String>(getApplicationContext(), R.layout.item, item);
                list.setAdapter(adapter);
    }
    
    /** Metoda odpowiedzialna za parsowanie pliku xml */
    private void parseXml(String strUrl) {
        try {
                        URL xmlUrl = new URL(strUrl);
                        
                        SAXParserFactory saxFactory = SAXParserFactory.newInstance();
                        SAXParser parser = saxFactory.newSAXParser();
                        XMLReader reader = parser.getXMLReader();
                        
                        RSSHandler myRSSHandler = new RSSHandler();
                        reader.setContentHandler(myRSSHandler);
                        
                        InputSource inputSource = new InputSource(xmlUrl.openStream());
                        reader.parse(inputSource);
                        
                } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), 
                                        "Plik rss nie mógł zostać przeczytany.", Toast.LENGTH_LONG).show();
                }
    }
}